package com.mucd.blogblogs7000.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mucd.blog.annontion.NotNull;
import com.mucd.blog.entity.ArticleEntity;
import com.mucd.blog.entity.ClassifyEntity;
import com.mucd.blog.result.R;
import com.mucd.blogblogs7000.dao.BlogsDao;
import com.mucd.blogblogs7000.dao.ClassifyDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author mucd
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class ClassifyServiceImpl {
    @Resource
    private ClassifyDao classifyDao;

    @Resource
    private BlogsDao blogsDao;


    /**
     * 查询所有文章分类
     *
     * @return R
     */
    @Cacheable(value = "classifyList")//将分类放入缓存
    public R list() {
        return R.ok(classifyDao.selectList(null));
    }

    /**
     * 新增分类
     *
     * @param classifyEntity
     * @return
     */
    @CacheEvict(value = "classifyList", allEntries = true)
    public R save(ClassifyEntity classifyEntity) {
        int insert = classifyDao.insert(classifyEntity);
        if (insert <= 0) {
            return R.error("添加失败");
        }
        return R.ok("操作成功");
    }

    /**
     * 删除分类
     *
     * @param classId
     * @return
     */
    @CacheEvict(value = "classifyList", allEntries = true)
    public R deletes(List<Integer> classId) {
        int i = classifyDao.deleteBatchIds(classId);
        if (i <= 0) {
            return R.error("删除失败");
        }
        return R.ok("操作成功");
    }

    /**
     * 修改分类
     *
     * @param classifyEntity
     * @return
     */
    @CacheEvict(value = "classifyList", allEntries = true)
    public R update(ClassifyEntity classifyEntity) {
        int i = classifyDao.updateById(classifyEntity);
        if (i <= 0) {
            return R.error("修改失败");
        }
        return R.ok("操作成功");
    }

    /**
     * 获取用户的文章的分类
     *
     * @param username
     * @return
     */
    public R getClassifyByUserByBlogs(@NotNull String username) {
        QueryWrapper<ArticleEntity> qw = new QueryWrapper<>();
        qw.eq("article_username", username);

        //按照名字获取所有的文章
        List<ArticleEntity> articleEntities = blogsDao.selectList(qw);

        //去除重复
        Set<String> list = new HashSet<>();

        //获取分类
        for (ArticleEntity articleEntity : articleEntities) {
            list.add(articleEntity.getArticleClassify());
        }

        return R.ok(list);
    }
}
